home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / subprocess.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  34KB  |  1,208 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''subprocess - Subprocesses with accessible I/O streams
  5.  
  6. This module allows you to spawn processes, connect to their
  7. input/output/error pipes, and obtain their return codes.  This module
  8. intends to replace several other, older modules and functions, like:
  9.  
  10. os.system
  11. os.spawn*
  12. os.popen*
  13. popen2.*
  14. commands.*
  15.  
  16. Information about how the subprocess module can be used to replace these
  17. modules and functions can be found below.
  18.  
  19.  
  20.  
  21. Using the subprocess module
  22. ===========================
  23. This module defines one class called Popen:
  24.  
  25. class Popen(args, bufsize=0, executable=None,
  26.             stdin=None, stdout=None, stderr=None,
  27.             preexec_fn=None, close_fds=False, shell=False,
  28.             cwd=None, env=None, universal_newlines=False,
  29.             startupinfo=None, creationflags=0):
  30.  
  31.  
  32. Arguments are:
  33.  
  34. args should be a string, or a sequence of program arguments.  The
  35. program to execute is normally the first item in the args sequence or
  36. string, but can be explicitly set by using the executable argument.
  37.  
  38. On UNIX, with shell=False (default): In this case, the Popen class
  39. uses os.execvp() to execute the child program.  args should normally
  40. be a sequence.  A string will be treated as a sequence with the string
  41. as the only item (the program to execute).
  42.  
  43. On UNIX, with shell=True: If args is a string, it specifies the
  44. command string to execute through the shell.  If args is a sequence,
  45. the first item specifies the command string, and any additional items
  46. will be treated as additional shell arguments.
  47.  
  48. On Windows: the Popen class uses CreateProcess() to execute the child
  49. program, which operates on strings.  If args is a sequence, it will be
  50. converted to a string using the list2cmdline method.  Please note that
  51. not all MS Windows applications interpret the command line the same
  52. way: The list2cmdline is designed for applications using the same
  53. rules as the MS C runtime.
  54.  
  55. bufsize, if given, has the same meaning as the corresponding argument
  56. to the built-in open() function: 0 means unbuffered, 1 means line
  57. buffered, any other positive value means use a buffer of
  58. (approximately) that size.  A negative bufsize means to use the system
  59. default, which usually means fully buffered.  The default value for
  60. bufsize is 0 (unbuffered).
  61.  
  62. stdin, stdout and stderr specify the executed programs\' standard
  63. input, standard output and standard error file handles, respectively.
  64. Valid values are PIPE, an existing file descriptor (a positive
  65. integer), an existing file object, and None.  PIPE indicates that a
  66. new pipe to the child should be created.  With None, no redirection
  67. will occur; the child\'s file handles will be inherited from the
  68. parent.  Additionally, stderr can be STDOUT, which indicates that the
  69. stderr data from the applications should be captured into the same
  70. file handle as for stdout.
  71.  
  72. If preexec_fn is set to a callable object, this object will be called
  73. in the child process just before the child is executed.
  74.  
  75. If close_fds is true, all file descriptors except 0, 1 and 2 will be
  76. closed before the child process is executed.
  77.  
  78. if shell is true, the specified command will be executed through the
  79. shell.
  80.  
  81. If cwd is not None, the current directory will be changed to cwd
  82. before the child is executed.
  83.  
  84. If env is not None, it defines the environment variables for the new
  85. process.
  86.  
  87. If universal_newlines is true, the file objects stdout and stderr are
  88. opened as a text files, but lines may be terminated by any of \'\\n\',
  89. the Unix end-of-line convention, \'\\r\', the Macintosh convention or
  90. \'\\r\\n\', the Windows convention.  All of these external representations
  91. are seen as \'\\n\' by the Python program.  Note: This feature is only
  92. available if Python is built with universal newline support (the
  93. default).  Also, the newlines attribute of the file objects stdout,
  94. stdin and stderr are not updated by the communicate() method.
  95.  
  96. The startupinfo and creationflags, if given, will be passed to the
  97. underlying CreateProcess() function.  They can specify things such as
  98. appearance of the main window and priority for the new process.
  99. (Windows only)
  100.  
  101.  
  102. This module also defines two shortcut functions:
  103.  
  104. call(*popenargs, **kwargs):
  105.     Run command with arguments.  Wait for command to complete, then
  106.     return the returncode attribute.
  107.  
  108.     The arguments are the same as for the Popen constructor.  Example:
  109.  
  110.     retcode = call(["ls", "-l"])
  111.  
  112. check_call(*popenargs, **kwargs):
  113.     Run command with arguments.  Wait for command to complete.  If the
  114.     exit code was zero then return, otherwise raise
  115.     CalledProcessError.  The CalledProcessError object will have the
  116.     return code in the returncode attribute.
  117.  
  118.     The arguments are the same as for the Popen constructor.  Example:
  119.  
  120.     check_call(["ls", "-l"])
  121.  
  122. Exceptions
  123. ----------
  124. Exceptions raised in the child process, before the new program has
  125. started to execute, will be re-raised in the parent.  Additionally,
  126. the exception object will have one extra attribute called
  127. \'child_traceback\', which is a string containing traceback information
  128. from the childs point of view.
  129.  
  130. The most common exception raised is OSError.  This occurs, for
  131. example, when trying to execute a non-existent file.  Applications
  132. should prepare for OSErrors.
  133.  
  134. A ValueError will be raised if Popen is called with invalid arguments.
  135.  
  136. check_call() will raise CalledProcessError, if the called process
  137. returns a non-zero return code.
  138.  
  139.  
  140. Security
  141. --------
  142. Unlike some other popen functions, this implementation will never call
  143. /bin/sh implicitly.  This means that all characters, including shell
  144. metacharacters, can safely be passed to child processes.
  145.  
  146.  
  147. Popen objects
  148. =============
  149. Instances of the Popen class have the following methods:
  150.  
  151. poll()
  152.     Check if child process has terminated.  Returns returncode
  153.     attribute.
  154.  
  155. wait()
  156.     Wait for child process to terminate.  Returns returncode attribute.
  157.  
  158. communicate(input=None)
  159.     Interact with process: Send data to stdin.  Read data from stdout
  160.     and stderr, until end-of-file is reached.  Wait for process to
  161.     terminate.  The optional input argument should be a string to be
  162.     sent to the child process, or None, if no data should be sent to
  163.     the child.
  164.  
  165.     communicate() returns a tuple (stdout, stderr).
  166.  
  167.     Note: The data read is buffered in memory, so do not use this
  168.     method if the data size is large or unlimited.
  169.  
  170. The following attributes are also available:
  171.  
  172. stdin
  173.     If the stdin argument is PIPE, this attribute is a file object
  174.     that provides input to the child process.  Otherwise, it is None.
  175.  
  176. stdout
  177.     If the stdout argument is PIPE, this attribute is a file object
  178.     that provides output from the child process.  Otherwise, it is
  179.     None.
  180.  
  181. stderr
  182.     If the stderr argument is PIPE, this attribute is file object that
  183.     provides error output from the child process.  Otherwise, it is
  184.     None.
  185.  
  186. pid
  187.     The process ID of the child process.
  188.  
  189. returncode
  190.     The child return code.  A None value indicates that the process
  191.     hasn\'t terminated yet.  A negative value -N indicates that the
  192.     child was terminated by signal N (UNIX only).
  193.  
  194.  
  195. Replacing older functions with the subprocess module
  196. ====================================================
  197. In this section, "a ==> b" means that b can be used as a replacement
  198. for a.
  199.  
  200. Note: All functions in this section fail (more or less) silently if
  201. the executed program cannot be found; this module raises an OSError
  202. exception.
  203.  
  204. In the following examples, we assume that the subprocess module is
  205. imported with "from subprocess import *".
  206.  
  207.  
  208. Replacing /bin/sh shell backquote
  209. ---------------------------------
  210. output=`mycmd myarg`
  211. ==>
  212. output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
  213.  
  214.  
  215. Replacing shell pipe line
  216. -------------------------
  217. output=`dmesg | grep hda`
  218. ==>
  219. p1 = Popen(["dmesg"], stdout=PIPE)
  220. p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  221. output = p2.communicate()[0]
  222.  
  223.  
  224. Replacing os.system()
  225. ---------------------
  226. sts = os.system("mycmd" + " myarg")
  227. ==>
  228. p = Popen("mycmd" + " myarg", shell=True)
  229. pid, sts = os.waitpid(p.pid, 0)
  230.  
  231. Note:
  232.  
  233. * Calling the program through the shell is usually not required.
  234.  
  235. * It\'s easier to look at the returncode attribute than the
  236.   exitstatus.
  237.  
  238. A more real-world example would look like this:
  239.  
  240. try:
  241.     retcode = call("mycmd" + " myarg", shell=True)
  242.     if retcode < 0:
  243.         print >>sys.stderr, "Child was terminated by signal", -retcode
  244.     else:
  245.         print >>sys.stderr, "Child returned", retcode
  246. except OSError, e:
  247.     print >>sys.stderr, "Execution failed:", e
  248.  
  249.  
  250. Replacing os.spawn*
  251. -------------------
  252. P_NOWAIT example:
  253.  
  254. pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
  255. ==>
  256. pid = Popen(["/bin/mycmd", "myarg"]).pid
  257.  
  258.  
  259. P_WAIT example:
  260.  
  261. retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
  262. ==>
  263. retcode = call(["/bin/mycmd", "myarg"])
  264.  
  265.  
  266. Vector example:
  267.  
  268. os.spawnvp(os.P_NOWAIT, path, args)
  269. ==>
  270. Popen([path] + args[1:])
  271.  
  272.  
  273. Environment example:
  274.  
  275. os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
  276. ==>
  277. Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
  278.  
  279.  
  280. Replacing os.popen*
  281. -------------------
  282. pipe = os.popen("cmd", mode=\'r\', bufsize)
  283. ==>
  284. pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
  285.  
  286. pipe = os.popen("cmd", mode=\'w\', bufsize)
  287. ==>
  288. pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
  289.  
  290.  
  291. (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
  292. ==>
  293. p = Popen("cmd", shell=True, bufsize=bufsize,
  294.           stdin=PIPE, stdout=PIPE, close_fds=True)
  295. (child_stdin, child_stdout) = (p.stdin, p.stdout)
  296.  
  297.  
  298. (child_stdin,
  299.  child_stdout,
  300.  child_stderr) = os.popen3("cmd", mode, bufsize)
  301. ==>
  302. p = Popen("cmd", shell=True, bufsize=bufsize,
  303.           stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
  304. (child_stdin,
  305.  child_stdout,
  306.  child_stderr) = (p.stdin, p.stdout, p.stderr)
  307.  
  308.  
  309. (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
  310.                                                    bufsize)
  311. ==>
  312. p = Popen("cmd", shell=True, bufsize=bufsize,
  313.           stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  314. (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
  315.  
  316. On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
  317. the command to execute, in which case arguments will be passed
  318. directly to the program without shell intervention.  This usage can be
  319. replaced as follows:
  320.  
  321. (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
  322.                                         bufsize)
  323. ==>
  324. p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
  325. (child_stdin, child_stdout) = (p.stdin, p.stdout)
  326.  
  327. Return code handling translates as follows:
  328.  
  329. pipe = os.popen("cmd", \'w\')
  330. ...
  331. rc = pipe.close()
  332. if rc != None and rc % 256:
  333.     print "There were some errors"
  334. ==>
  335. process = Popen("cmd", \'w\', shell=True, stdin=PIPE)
  336. ...
  337. process.stdin.close()
  338. if process.wait() != 0:
  339.     print "There were some errors"
  340.  
  341.  
  342. Replacing popen2.*
  343. ------------------
  344. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
  345. ==>
  346. p = Popen(["somestring"], shell=True, bufsize=bufsize
  347.           stdin=PIPE, stdout=PIPE, close_fds=True)
  348. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  349.  
  350. On Unix, popen2 also accepts a sequence as the command to execute, in
  351. which case arguments will be passed directly to the program without
  352. shell intervention.  This usage can be replaced as follows:
  353.  
  354. (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
  355.                                             mode)
  356. ==>
  357. p = Popen(["mycmd", "myarg"], bufsize=bufsize,
  358.           stdin=PIPE, stdout=PIPE, close_fds=True)
  359. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  360.  
  361. The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
  362. except that:
  363.  
  364. * subprocess.Popen raises an exception if the execution fails
  365. * the capturestderr argument is replaced with the stderr argument.
  366. * stdin=PIPE and stdout=PIPE must be specified.
  367. * popen2 closes all filedescriptors by default, but you have to specify
  368.   close_fds=True with subprocess.Popen.
  369. '''
  370. import sys
  371. mswindows = sys.platform == 'win32'
  372. import os
  373. import types
  374. import traceback
  375. import gc
  376. import signal
  377.  
  378. class CalledProcessError(Exception):
  379.     '''This exception is raised when a process run by check_call() returns
  380.     a non-zero exit status.  The exit status will be stored in the
  381.     returncode attribute.'''
  382.     
  383.     def __init__(self, returncode, cmd):
  384.         self.returncode = returncode
  385.         self.cmd = cmd
  386.  
  387.     
  388.     def __str__(self):
  389.         return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
  390.  
  391.  
  392. if mswindows:
  393.     import threading
  394.     import msvcrt
  395.     from _subprocess import *
  396.     
  397.     class STARTUPINFO:
  398.         dwFlags = 0
  399.         hStdInput = None
  400.         hStdOutput = None
  401.         hStdError = None
  402.         wShowWindow = 0
  403.  
  404.     
  405.     class pywintypes:
  406.         error = IOError
  407.  
  408. else:
  409.     import select
  410.     import errno
  411.     import fcntl
  412.     import pickle
  413. __all__ = [
  414.     'Popen',
  415.     'PIPE',
  416.     'STDOUT',
  417.     'call',
  418.     'check_call',
  419.     'CalledProcessError']
  420.  
  421. try:
  422.     MAXFD = os.sysconf('SC_OPEN_MAX')
  423. except:
  424.     MAXFD = 256
  425.  
  426. _active = []
  427.  
  428. def _cleanup():
  429.     for inst in _active[:]:
  430.         if inst._internal_poll(_deadstate = sys.maxint) >= 0:
  431.             
  432.             try:
  433.                 _active.remove(inst)
  434.             except ValueError:
  435.                 pass
  436.             except:
  437.                 None<EXCEPTION MATCH>ValueError
  438.             
  439.  
  440.         None<EXCEPTION MATCH>ValueError
  441.     
  442.  
  443. PIPE = -1
  444. STDOUT = -2
  445.  
  446. def call(*popenargs, **kwargs):
  447.     '''Run command with arguments.  Wait for command to complete, then
  448.     return the returncode attribute.
  449.  
  450.     The arguments are the same as for the Popen constructor.  Example:
  451.  
  452.     retcode = call(["ls", "-l"])
  453.     '''
  454.     return Popen(*popenargs, **kwargs).wait()
  455.  
  456.  
  457. def check_call(*popenargs, **kwargs):
  458.     '''Run command with arguments.  Wait for command to complete.  If
  459.     the exit code was zero then return, otherwise raise
  460.     CalledProcessError.  The CalledProcessError object will have the
  461.     return code in the returncode attribute.
  462.  
  463.     The arguments are the same as for the Popen constructor.  Example:
  464.  
  465.     check_call(["ls", "-l"])
  466.     '''
  467.     retcode = call(*popenargs, **kwargs)
  468.     cmd = kwargs.get('args')
  469.     if cmd is None:
  470.         cmd = popenargs[0]
  471.     
  472.     if retcode:
  473.         raise CalledProcessError(retcode, cmd)
  474.     retcode
  475.     return retcode
  476.  
  477.  
  478. def list2cmdline(seq):
  479.     '''
  480.     Translate a sequence of arguments into a command line
  481.     string, using the same rules as the MS C runtime:
  482.  
  483.     1) Arguments are delimited by white space, which is either a
  484.        space or a tab.
  485.  
  486.     2) A string surrounded by double quotation marks is
  487.        interpreted as a single argument, regardless of white space
  488.        or pipe characters contained within.  A quoted string can be
  489.        embedded in an argument.
  490.  
  491.     3) A double quotation mark preceded by a backslash is
  492.        interpreted as a literal double quotation mark.
  493.  
  494.     4) Backslashes are interpreted literally, unless they
  495.        immediately precede a double quotation mark.
  496.  
  497.     5) If backslashes immediately precede a double quotation mark,
  498.        every pair of backslashes is interpreted as a literal
  499.        backslash.  If the number of backslashes is odd, the last
  500.        backslash escapes the next double quotation mark as
  501.        described in rule 3.
  502.     '''
  503.     result = []
  504.     needquote = False
  505.     for arg in seq:
  506.         bs_buf = []
  507.         if result:
  508.             result.append(' ')
  509.         
  510.         if not ' ' in arg and '\t' in arg and '|' in arg:
  511.             pass
  512.         needquote = not arg
  513.         if needquote:
  514.             result.append('"')
  515.         
  516.         for c in arg:
  517.             if c == '\\':
  518.                 bs_buf.append(c)
  519.                 continue
  520.             if c == '"':
  521.                 result.append('\\' * len(bs_buf) * 2)
  522.                 bs_buf = []
  523.                 result.append('\\"')
  524.                 continue
  525.             if bs_buf:
  526.                 result.extend(bs_buf)
  527.                 bs_buf = []
  528.             
  529.             result.append(c)
  530.         
  531.         if bs_buf:
  532.             result.extend(bs_buf)
  533.         
  534.         if needquote:
  535.             result.extend(bs_buf)
  536.             result.append('"')
  537.             continue
  538.     
  539.     return ''.join(result)
  540.  
  541.  
  542. class Popen(object):
  543.     
  544.     def __init__(self, args, bufsize = 0, executable = None, stdin = None, stdout = None, stderr = None, preexec_fn = None, close_fds = False, shell = False, cwd = None, env = None, universal_newlines = False, startupinfo = None, creationflags = 0):
  545.         '''Create new Popen instance.'''
  546.         _cleanup()
  547.         self._child_created = False
  548.         if not isinstance(bufsize, (int, long)):
  549.             raise TypeError('bufsize must be an integer')
  550.         isinstance(bufsize, (int, long))
  551.         if mswindows:
  552.             if preexec_fn is not None:
  553.                 raise ValueError('preexec_fn is not supported on Windows platforms')
  554.             preexec_fn is not None
  555.             if close_fds:
  556.                 if stdin is not None and stdout is not None or stderr is not None:
  557.                     raise ValueError('close_fds is not supported on Windows platforms if you redirect stdin/stdout/stderr')
  558.             stderr is not None
  559.         elif startupinfo is not None:
  560.             raise ValueError('startupinfo is only supported on Windows platforms')
  561.         
  562.         if creationflags != 0:
  563.             raise ValueError('creationflags is only supported on Windows platforms')
  564.         creationflags != 0
  565.         self.stdin = None
  566.         self.stdout = None
  567.         self.stderr = None
  568.         self.pid = None
  569.         self.returncode = None
  570.         self.universal_newlines = universal_newlines
  571.         (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  572.         self._execute_child(args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  573.         if mswindows:
  574.             if p2cwrite is not None:
  575.                 p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
  576.             
  577.             if c2pread is not None:
  578.                 c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
  579.             
  580.             if errread is not None:
  581.                 errread = msvcrt.open_osfhandle(errread.Detach(), 0)
  582.             
  583.         
  584.         if p2cwrite is not None:
  585.             self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
  586.         
  587.         if c2pread is not None:
  588.             if universal_newlines:
  589.                 self.stdout = os.fdopen(c2pread, 'rU', bufsize)
  590.             else:
  591.                 self.stdout = os.fdopen(c2pread, 'rb', bufsize)
  592.         
  593.         if errread is not None:
  594.             if universal_newlines:
  595.                 self.stderr = os.fdopen(errread, 'rU', bufsize)
  596.             else:
  597.                 self.stderr = os.fdopen(errread, 'rb', bufsize)
  598.         
  599.  
  600.     
  601.     def _translate_newlines(self, data):
  602.         data = data.replace('\r\n', '\n')
  603.         data = data.replace('\r', '\n')
  604.         return data
  605.  
  606.     
  607.     def __del__(self, sys = sys):
  608.         if not self._child_created:
  609.             return None
  610.         self._internal_poll(_deadstate = sys.maxint)
  611.         if self.returncode is None and _active is not None:
  612.             _active.append(self)
  613.         
  614.  
  615.     
  616.     def communicate(self, input = None):
  617.         '''Interact with process: Send data to stdin.  Read data from
  618.         stdout and stderr, until end-of-file is reached.  Wait for
  619.         process to terminate.  The optional input argument should be a
  620.         string to be sent to the child process, or None, if no data
  621.         should be sent to the child.
  622.  
  623.         communicate() returns a tuple (stdout, stderr).'''
  624.         if [
  625.             self.stdin,
  626.             self.stdout,
  627.             self.stderr].count(None) >= 2:
  628.             stdout = None
  629.             stderr = None
  630.             if self.stdin:
  631.                 if input:
  632.                     self.stdin.write(input)
  633.                 
  634.                 self.stdin.close()
  635.             elif self.stdout:
  636.                 stdout = self.stdout.read()
  637.                 self.stdout.close()
  638.             elif self.stderr:
  639.                 stderr = self.stderr.read()
  640.                 self.stderr.close()
  641.             
  642.             self.wait()
  643.             return (stdout, stderr)
  644.         return self._communicate(input)
  645.  
  646.     
  647.     def poll(self):
  648.         return self._internal_poll()
  649.  
  650.     if mswindows:
  651.         
  652.         def _get_handles(self, stdin, stdout, stderr):
  653.             '''Construct and return tupel with IO objects:
  654.             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  655.             '''
  656.             if stdin is None and stdout is None and stderr is None:
  657.                 return (None, None, None, None, None, None)
  658.             (p2cread, p2cwrite) = (None, None)
  659.             (c2pread, c2pwrite) = (None, None)
  660.             (errread, errwrite) = (None, None)
  661.             if stdin is None:
  662.                 p2cread = GetStdHandle(STD_INPUT_HANDLE)
  663.                 if p2cread is None:
  664.                     (p2cread, _) = CreatePipe(None, 0)
  665.                 
  666.             elif stdin == PIPE:
  667.                 (p2cread, p2cwrite) = CreatePipe(None, 0)
  668.             elif isinstance(stdin, int):
  669.                 p2cread = msvcrt.get_osfhandle(stdin)
  670.             else:
  671.                 p2cread = msvcrt.get_osfhandle(stdin.fileno())
  672.             p2cread = self._make_inheritable(p2cread)
  673.             if stdout is None:
  674.                 c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
  675.                 if c2pwrite is None:
  676.                     (_, c2pwrite) = CreatePipe(None, 0)
  677.                 
  678.             elif stdout == PIPE:
  679.                 (c2pread, c2pwrite) = CreatePipe(None, 0)
  680.             elif isinstance(stdout, int):
  681.                 c2pwrite = msvcrt.get_osfhandle(stdout)
  682.             else:
  683.                 c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  684.             c2pwrite = self._make_inheritable(c2pwrite)
  685.             if stderr is None:
  686.                 errwrite = GetStdHandle(STD_ERROR_HANDLE)
  687.                 if errwrite is None:
  688.                     (_, errwrite) = CreatePipe(None, 0)
  689.                 
  690.             elif stderr == PIPE:
  691.                 (errread, errwrite) = CreatePipe(None, 0)
  692.             elif stderr == STDOUT:
  693.                 errwrite = c2pwrite
  694.             elif isinstance(stderr, int):
  695.                 errwrite = msvcrt.get_osfhandle(stderr)
  696.             else:
  697.                 errwrite = msvcrt.get_osfhandle(stderr.fileno())
  698.             errwrite = self._make_inheritable(errwrite)
  699.             return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  700.  
  701.         
  702.         def _make_inheritable(self, handle):
  703.             '''Return a duplicate of handle, which is inheritable'''
  704.             return DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), 0, 1, DUPLICATE_SAME_ACCESS)
  705.  
  706.         
  707.         def _find_w9xpopen(self):
  708.             '''Find and return absolut path to w9xpopen.exe'''
  709.             w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)), 'w9xpopen.exe')
  710.             if not os.path.exists(w9xpopen):
  711.                 w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), 'w9xpopen.exe')
  712.                 if not os.path.exists(w9xpopen):
  713.                     raise RuntimeError('Cannot locate w9xpopen.exe, which is needed for Popen to work with your shell or platform.')
  714.                 os.path.exists(w9xpopen)
  715.             
  716.             return w9xpopen
  717.  
  718.         
  719.         def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite):
  720.             '''Execute program (MS Windows version)'''
  721.             if not isinstance(args, types.StringTypes):
  722.                 args = list2cmdline(args)
  723.             
  724.             if startupinfo is None:
  725.                 startupinfo = STARTUPINFO()
  726.             
  727.             if None not in (p2cread, c2pwrite, errwrite):
  728.                 startupinfo.dwFlags |= STARTF_USESTDHANDLES
  729.                 startupinfo.hStdInput = p2cread
  730.                 startupinfo.hStdOutput = c2pwrite
  731.                 startupinfo.hStdError = errwrite
  732.             
  733.             if shell:
  734.                 startupinfo.dwFlags |= STARTF_USESHOWWINDOW
  735.                 startupinfo.wShowWindow = SW_HIDE
  736.                 comspec = os.environ.get('COMSPEC', 'cmd.exe')
  737.                 args = comspec + ' /c ' + args
  738.                 if GetVersion() >= 0x80000000L or os.path.basename(comspec).lower() == 'command.com':
  739.                     w9xpopen = self._find_w9xpopen()
  740.                     args = '"%s" %s' % (w9xpopen, args)
  741.                     creationflags |= CREATE_NEW_CONSOLE
  742.                 
  743.             
  744.             
  745.             try:
  746.                 (hp, ht, pid, tid) = CreateProcess(executable, args, None, None, int(not close_fds), creationflags, env, cwd, startupinfo)
  747.             except pywintypes.error:
  748.                 e = None
  749.                 raise WindowsError(*e.args)
  750.  
  751.             self._child_created = True
  752.             self._handle = hp
  753.             self.pid = pid
  754.             ht.Close()
  755.             if p2cread is not None:
  756.                 p2cread.Close()
  757.             
  758.             if c2pwrite is not None:
  759.                 c2pwrite.Close()
  760.             
  761.             if errwrite is not None:
  762.                 errwrite.Close()
  763.             
  764.  
  765.         
  766.         def _internal_poll(self, _deadstate = None):
  767.             '''Check if child process has terminated.  Returns returncode
  768.             attribute.'''
  769.             if self.returncode is None:
  770.                 if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
  771.                     self.returncode = GetExitCodeProcess(self._handle)
  772.                 
  773.             
  774.             return self.returncode
  775.  
  776.         
  777.         def wait(self):
  778.             '''Wait for child process to terminate.  Returns returncode
  779.             attribute.'''
  780.             if self.returncode is None:
  781.                 obj = WaitForSingleObject(self._handle, INFINITE)
  782.                 self.returncode = GetExitCodeProcess(self._handle)
  783.             
  784.             return self.returncode
  785.  
  786.         
  787.         def _readerthread(self, fh, buffer):
  788.             buffer.append(fh.read())
  789.  
  790.         
  791.         def _communicate(self, input):
  792.             stdout = None
  793.             stderr = None
  794.             if self.stdout:
  795.                 stdout = []
  796.                 stdout_thread = threading.Thread(target = self._readerthread, args = (self.stdout, stdout))
  797.                 stdout_thread.setDaemon(True)
  798.                 stdout_thread.start()
  799.             
  800.             if self.stderr:
  801.                 stderr = []
  802.                 stderr_thread = threading.Thread(target = self._readerthread, args = (self.stderr, stderr))
  803.                 stderr_thread.setDaemon(True)
  804.                 stderr_thread.start()
  805.             
  806.             if self.stdin:
  807.                 if input is not None:
  808.                     self.stdin.write(input)
  809.                 
  810.                 self.stdin.close()
  811.             
  812.             if self.stdout:
  813.                 stdout_thread.join()
  814.             
  815.             if self.stderr:
  816.                 stderr_thread.join()
  817.             
  818.             if stdout is not None:
  819.                 stdout = stdout[0]
  820.             
  821.             if stderr is not None:
  822.                 stderr = stderr[0]
  823.             
  824.             if self.universal_newlines and hasattr(file, 'newlines'):
  825.                 if stdout:
  826.                     stdout = self._translate_newlines(stdout)
  827.                 
  828.                 if stderr:
  829.                     stderr = self._translate_newlines(stderr)
  830.                 
  831.             
  832.             self.wait()
  833.             return (stdout, stderr)
  834.  
  835.         
  836.         def send_signal(self, sig):
  837.             '''Send a signal to the process
  838.             '''
  839.             if sig == signal.SIGTERM:
  840.                 self.terminate()
  841.             else:
  842.                 raise ValueError('Only SIGTERM is supported on Windows')
  843.             return sig == signal.SIGTERM
  844.  
  845.         
  846.         def terminate(self):
  847.             '''Terminates the process
  848.             '''
  849.             TerminateProcess(self._handle, 1)
  850.  
  851.         kill = terminate
  852.     else:
  853.         
  854.         def _get_handles(self, stdin, stdout, stderr):
  855.             '''Construct and return tupel with IO objects:
  856.             p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  857.             '''
  858.             (p2cread, p2cwrite) = (None, None)
  859.             (c2pread, c2pwrite) = (None, None)
  860.             (errread, errwrite) = (None, None)
  861.             if stdin is None:
  862.                 pass
  863.             elif stdin == PIPE:
  864.                 (p2cread, p2cwrite) = os.pipe()
  865.             elif isinstance(stdin, int):
  866.                 p2cread = stdin
  867.             else:
  868.                 p2cread = stdin.fileno()
  869.             if stdout is None:
  870.                 pass
  871.             elif stdout == PIPE:
  872.                 (c2pread, c2pwrite) = os.pipe()
  873.             elif isinstance(stdout, int):
  874.                 c2pwrite = stdout
  875.             else:
  876.                 c2pwrite = stdout.fileno()
  877.             if stderr is None:
  878.                 pass
  879.             elif stderr == PIPE:
  880.                 (errread, errwrite) = os.pipe()
  881.             elif stderr == STDOUT:
  882.                 errwrite = c2pwrite
  883.             elif isinstance(stderr, int):
  884.                 errwrite = stderr
  885.             else:
  886.                 errwrite = stderr.fileno()
  887.             return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
  888.  
  889.         
  890.         def _set_cloexec_flag(self, fd):
  891.             
  892.             try:
  893.                 cloexec_flag = fcntl.FD_CLOEXEC
  894.             except AttributeError:
  895.                 cloexec_flag = 1
  896.  
  897.             old = fcntl.fcntl(fd, fcntl.F_GETFD)
  898.             fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
  899.  
  900.         
  901.         def _close_fds(self, but):
  902.             os.closerange(3, but)
  903.             os.closerange(but + 1, MAXFD)
  904.  
  905.         
  906.         def _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite):
  907.             '''Execute program (POSIX version)'''
  908.             if isinstance(args, types.StringTypes):
  909.                 args = [
  910.                     args]
  911.             else:
  912.                 args = list(args)
  913.             if shell:
  914.                 args = [
  915.                     '/bin/sh',
  916.                     '-c'] + args
  917.             
  918.             if executable is None:
  919.                 executable = args[0]
  920.             
  921.             (errpipe_read, errpipe_write) = os.pipe()
  922.             
  923.             try:
  924.                 
  925.                 try:
  926.                     self._set_cloexec_flag(errpipe_write)
  927.                     gc_was_enabled = gc.isenabled()
  928.                     gc.disable()
  929.                     
  930.                     try:
  931.                         self.pid = os.fork()
  932.                     except:
  933.                         if gc_was_enabled:
  934.                             gc.enable()
  935.                         
  936.                         raise 
  937.  
  938.                     self._child_created = True
  939.                     if self.pid == 0:
  940.                         
  941.                         try:
  942.                             if p2cwrite is not None:
  943.                                 os.close(p2cwrite)
  944.                             
  945.                             if c2pread is not None:
  946.                                 os.close(c2pread)
  947.                             
  948.                             if errread is not None:
  949.                                 os.close(errread)
  950.                             
  951.                             os.close(errpipe_read)
  952.                             if p2cread is not None:
  953.                                 os.dup2(p2cread, 0)
  954.                             
  955.                             if c2pwrite is not None:
  956.                                 os.dup2(c2pwrite, 1)
  957.                             
  958.                             if errwrite is not None:
  959.                                 os.dup2(errwrite, 2)
  960.                             
  961.                             if p2cread is not None and p2cread not in (0,):
  962.                                 os.close(p2cread)
  963.                             
  964.                             if c2pwrite is not None and c2pwrite not in (p2cread, 1):
  965.                                 os.close(c2pwrite)
  966.                             
  967.                             if errwrite is not None and errwrite not in (p2cread, c2pwrite, 2):
  968.                                 os.close(errwrite)
  969.                             
  970.                             if close_fds:
  971.                                 self._close_fds(but = errpipe_write)
  972.                             
  973.                             if cwd is not None:
  974.                                 os.chdir(cwd)
  975.                             
  976.                             if preexec_fn:
  977.                                 preexec_fn()
  978.                             
  979.                             if env is None:
  980.                                 os.execvp(executable, args)
  981.                             else:
  982.                                 os.execvpe(executable, args, env)
  983.                         except:
  984.                             (exc_type, exc_value, tb) = sys.exc_info()
  985.                             exc_lines = traceback.format_exception(exc_type, exc_value, tb)
  986.                             exc_value.child_traceback = ''.join(exc_lines)
  987.                             os.write(errpipe_write, pickle.dumps(exc_value))
  988.  
  989.                         os._exit(255)
  990.                     
  991.                     if gc_was_enabled:
  992.                         gc.enable()
  993.                 finally:
  994.                     os.close(errpipe_write)
  995.  
  996.                 if p2cread is not None and p2cwrite is not None:
  997.                     os.close(p2cread)
  998.                 
  999.                 if c2pwrite is not None and c2pread is not None:
  1000.                     os.close(c2pwrite)
  1001.                 
  1002.                 if errwrite is not None and errread is not None:
  1003.                     os.close(errwrite)
  1004.                 
  1005.                 data = os.read(errpipe_read, 1048576)
  1006.             finally:
  1007.                 os.close(errpipe_read)
  1008.  
  1009.             if data != '':
  1010.                 os.waitpid(self.pid, 0)
  1011.                 child_exception = pickle.loads(data)
  1012.                 for fd in (p2cwrite, c2pread, errread):
  1013.                     if fd is not None:
  1014.                         os.close(fd)
  1015.                         continue
  1016.                 
  1017.                 raise child_exception
  1018.             data != ''
  1019.  
  1020.         
  1021.         def _handle_exitstatus(self, sts):
  1022.             if os.WIFSIGNALED(sts):
  1023.                 self.returncode = -os.WTERMSIG(sts)
  1024.             elif os.WIFEXITED(sts):
  1025.                 self.returncode = os.WEXITSTATUS(sts)
  1026.             else:
  1027.                 raise RuntimeError('Unknown child exit status!')
  1028.             return os.WIFSIGNALED(sts)
  1029.  
  1030.         
  1031.         def _internal_poll(self, _deadstate = None):
  1032.             '''Check if child process has terminated.  Returns returncode
  1033.             attribute.'''
  1034.             if self.returncode is None:
  1035.                 
  1036.                 try:
  1037.                     (pid, sts) = os.waitpid(self.pid, os.WNOHANG)
  1038.                     if pid == self.pid:
  1039.                         self._handle_exitstatus(sts)
  1040.                 except os.error:
  1041.                     if _deadstate is not None:
  1042.                         self.returncode = _deadstate
  1043.                     
  1044.                 except:
  1045.                     _deadstate is not None
  1046.                 
  1047.  
  1048.             None<EXCEPTION MATCH>os.error
  1049.             return self.returncode
  1050.  
  1051.         
  1052.         def wait(self):
  1053.             '''Wait for child process to terminate.  Returns returncode
  1054.             attribute.'''
  1055.             if self.returncode is None:
  1056.                 (pid, sts) = os.waitpid(self.pid, 0)
  1057.                 self._handle_exitstatus(sts)
  1058.             
  1059.             return self.returncode
  1060.  
  1061.         
  1062.         def _communicate(self, input):
  1063.             read_set = []
  1064.             write_set = []
  1065.             stdout = None
  1066.             stderr = None
  1067.             if self.stdin:
  1068.                 self.stdin.flush()
  1069.                 if input:
  1070.                     write_set.append(self.stdin)
  1071.                 else:
  1072.                     self.stdin.close()
  1073.             
  1074.             if self.stdout:
  1075.                 read_set.append(self.stdout)
  1076.                 stdout = []
  1077.             
  1078.             if self.stderr:
  1079.                 read_set.append(self.stderr)
  1080.                 stderr = []
  1081.             
  1082.             input_offset = 0
  1083.             while read_set or write_set:
  1084.                 
  1085.                 try:
  1086.                     (rlist, wlist, xlist) = select.select(read_set, write_set, [])
  1087.                 except select.error:
  1088.                     e = None
  1089.                     if e.args[0] == errno.EINTR:
  1090.                         continue
  1091.                     
  1092.                     raise 
  1093.  
  1094.                 if self.stdin in wlist:
  1095.                     chunk = input[input_offset:input_offset + 512]
  1096.                     bytes_written = os.write(self.stdin.fileno(), chunk)
  1097.                     input_offset += bytes_written
  1098.                     if input_offset >= len(input):
  1099.                         self.stdin.close()
  1100.                         write_set.remove(self.stdin)
  1101.                     
  1102.                 
  1103.                 if self.stdout in rlist:
  1104.                     data = os.read(self.stdout.fileno(), 1024)
  1105.                     if data == '':
  1106.                         self.stdout.close()
  1107.                         read_set.remove(self.stdout)
  1108.                     
  1109.                     stdout.append(data)
  1110.                 
  1111.                 if self.stderr in rlist:
  1112.                     data = os.read(self.stderr.fileno(), 1024)
  1113.                     if data == '':
  1114.                         self.stderr.close()
  1115.                         read_set.remove(self.stderr)
  1116.                     
  1117.                     stderr.append(data)
  1118.                     continue
  1119.             if stdout is not None:
  1120.                 stdout = ''.join(stdout)
  1121.             
  1122.             if stderr is not None:
  1123.                 stderr = ''.join(stderr)
  1124.             
  1125.             if self.universal_newlines and hasattr(file, 'newlines'):
  1126.                 if stdout:
  1127.                     stdout = self._translate_newlines(stdout)
  1128.                 
  1129.                 if stderr:
  1130.                     stderr = self._translate_newlines(stderr)
  1131.                 
  1132.             
  1133.             self.wait()
  1134.             return (stdout, stderr)
  1135.  
  1136.         
  1137.         def send_signal(self, sig):
  1138.             '''Send a signal to the process
  1139.             '''
  1140.             os.kill(self.pid, sig)
  1141.  
  1142.         
  1143.         def terminate(self):
  1144.             '''Terminate the process with SIGTERM
  1145.             '''
  1146.             self.send_signal(signal.SIGTERM)
  1147.  
  1148.         
  1149.         def kill(self):
  1150.             '''Kill the process with SIGKILL
  1151.             '''
  1152.             self.send_signal(signal.SIGKILL)
  1153.  
  1154.  
  1155.  
  1156. def _demo_posix():
  1157.     plist = Popen([
  1158.         'ps'], stdout = PIPE).communicate()[0]
  1159.     print 'Process list:'
  1160.     print plist
  1161.     if os.getuid() == 0:
  1162.         p = Popen([
  1163.             'id'], preexec_fn = (lambda : os.setuid(100)))
  1164.         p.wait()
  1165.     
  1166.     print "Looking for 'hda'..."
  1167.     p1 = Popen([
  1168.         'dmesg'], stdout = PIPE)
  1169.     p2 = Popen([
  1170.         'grep',
  1171.         'hda'], stdin = p1.stdout, stdout = PIPE)
  1172.     print repr(p2.communicate()[0])
  1173.     print 
  1174.     print 'Trying a weird file...'
  1175.     
  1176.     try:
  1177.         print Popen([
  1178.             '/this/path/does/not/exist']).communicate()
  1179.     except OSError:
  1180.         e = None
  1181.         if e.errno == errno.ENOENT:
  1182.             print "The file didn't exist.  I thought so..."
  1183.             print 'Child traceback:'
  1184.             print e.child_traceback
  1185.         else:
  1186.             print 'Error', e.errno
  1187.     except:
  1188.         e.errno == errno.ENOENT
  1189.  
  1190.     print >>sys.stderr, 'Gosh.  No error.'
  1191.  
  1192.  
  1193. def _demo_windows():
  1194.     print "Looking for 'PROMPT' in set output..."
  1195.     p1 = Popen('set', stdout = PIPE, shell = True)
  1196.     p2 = Popen('find "PROMPT"', stdin = p1.stdout, stdout = PIPE)
  1197.     print repr(p2.communicate()[0])
  1198.     print 'Executing calc...'
  1199.     p = Popen('calc')
  1200.     p.wait()
  1201.  
  1202. if __name__ == '__main__':
  1203.     if mswindows:
  1204.         _demo_windows()
  1205.     else:
  1206.         _demo_posix()
  1207.  
  1208.